Ext.define('UX.codeview.MultiCodeviewPopup', {
	extend : 'Ext.window.Window',
	alias : 'widget.multicodeviewpopup',
	cls : 'codeviewpopup',
	width : 650,
	height : 400,
	modal : true,
	layout : {
		type : 'vbox',
		align : 'stretch'
	},
	title : 'Code View',

	initComponent : function() {
		this.items = [ this.buildForm() ];

		this.callParent();

		var grdCodeList = this.down('#grdCodeList');
		var codeviewField = this.codeviewField;

		this.mon(this, {
			show : function() {
				codeviewField.fireEvent('showpopup', codeviewField, this);
				this.reconfigureGrdSelectCodeList();
				this.viewCodeList();
			},
			close : function() {
				codeviewField.fireEvent('closepopup', codeviewField);
				grdCodeList.getStore().removeAll();
			},
			afterstoreload : function(field, store, records, success) {
				if (success === true) {
					this.selectCodeList();
				}
			},
			scope : this
		});

		this.mon(grdCodeList, {
			itemclick : function(grid, record, item, index, e, eOpts) {
				var grdSelectCodeList = this.down('#grdSelectCodeList');
				var selectCodeListStore = grdSelectCodeList.getStore();

				var selModel = grdCodeList.getSelectionModel();
				if (selModel.isSelected(record) === true) {
					if (selectCodeListStore.getCount() >= this.pMultiSelectCount) {
						Ext.Msg.alert('Error', 'CHK-SELECTEDITEMSCOUNT');
						return;
					}
					this.addSelectedRecrod(record);
				} else {
					this.removeSelectedRecord(grdCodeList.itemId, record);
				}
			},
			scope : this
		});

		var btnClearSearchFields = this.down('#btnClearSearchFields');
		this.mon(btnClearSearchFields, {
			click : function() {
				this.clearSearchFields();
				this.viewCodeList();
			},
			scope : this
		});

		var btnReset = this.down('#btnReset');
		this.mon(btnReset, {
			click : function() {
				codeviewField.fireEvent('clearfieldvalue', codeviewField);
				this.close();
			},
			scope : this
		});

		var btnClear = this.down('#btnClear');
		this.mon(btnClear, {
			click : function() {
				var grdCodeList = this.down('#grdCodeList');
				var grdSelectCodeList = this.down('#grdSelectCodeList');
				var store = grdSelectCodeList.getStore();
				store.removeAll();
				grdCodeList.getSelectionModel().deselectAll();
			},
			scope : this
		});

		var btnOk = this.down('#btnOk');
		this.mon(btnOk, {
			click : function() {
				var grdSelectCodeList = this.down('#grdSelectCodeList');
				var store = grdSelectCodeList.getStore();
				var records = store.getRange();

				codeviewField.fireEvent('setfieldvalue', codeviewField, records);
				this.close();
			},
			scope : this
		});

		var btnClose = this.down('#btnClose');
		this.mon(btnClose, {
			click : function() {
				this.close();
			},
			scope : this
		});
	},

	viewCodeList : function(reload) {
		var grdCodeList = this.down('#grdCodeList');
		var store = grdCodeList.getStore();
		var params = Ext.clone(this.pParams) || {};

		store.clearFilter(true);
		store.currentPage = 1;
		var proxy = store.getProxy();
		if (params) {
			Ext.apply(proxy.extraParams, params);
		}

		function loadStore(scope) {
			store.load({
				showFailureMsg : scope.pShowFailureMsg,
				scope : scope
			});
		}

		if (this.pCdvType == 'gcm' || this.pCdvType == 'table') {
			var conditions = Ext.clone(params.condition) || Ext.clone(this.pCondition);
			conditions = Ext.Array.merge(conditions, this.getSearchFiedValues('conditions'));
			if (conditions.length < 1) {
				delete proxy.extraParams.condition;
			} else {
				proxy.extraParams.condition = conditions;
			}
			loadStore(this);
		} else {
			var filters = this.getSearchFiedValues('filters') || [];
			if (reload || filters.length < 1) {
				loadStore(this);
			} else {
				store.filter(filters);
			}
		}
	},

	selectCodeList : function() {
		var grdCodeList = this.down('#grdCodeList');
		var grdSelectCodeList = this.down('#grdSelectCodeList');
		var selectCodeListStore = grdSelectCodeList.getStore();
		var codeListStore = grdCodeList.getStore();
		var selModel = grdSelectCodeList.getSelectionModel();

		codeListStore.each(function(record) {
			var index = selectCodeListStore.findBy(function(rec) {
				if (selModel.isSelected(rec) === true) {
					return false;
				}
				return this.compareObjects(rec.data, record.data);
			}, this);

			if (index > -1) {
				grdCodeList.getSelectionModel().select(record, true);
				selModel.select(index, true);
			}
		}, this);

		selModel.deselectAll();
	},

	addSelectedRecrod : function(record) {
		var grdSelectCodeList = this.down('#grdSelectCodeList');
		var store = grdSelectCodeList.getStore();

		store.add(record.data);
	},

	removeSelectedRecord : function(grdItemId, record) {
		var grdCodeList = this.down('#grdCodeList');
		var grdSelectCodeList = this.down('#grdSelectCodeList');
		var codeListStore = grdCodeList.getStore();
		var selectCodeListStore = grdSelectCodeList.getStore();
		var selModel = grdCodeList.getSelectionModel();

		if (grdItemId == 'grdSelectCodeList') {
			// grdSelectCodeList record
			var index = codeListStore.findBy(function(rec) {
				if (selModel.isSelected(rec) === false) {
					return false;
				}
				return this.compareObjects(record.data, rec.data);
			}, this);

			if (index > -1) {
				selModel.deselect(index);
			}
			selectCodeListStore.remove(record);
		} else if (grdItemId == 'grdCodeList') {
			// grdCodeList record
			var index = selectCodeListStore.findBy(function(rec) {
				return this.compareObjects(rec.data, record.data);
			}, this);

			if (index > -1) {
				selectCodeListStore.remove(selectCodeListStore.getAt(index));
			}
		}
	},

	compareObjects : function(obj1, obj2) {
		for ( var p in obj1) {
			if (Ext.isEmpty(obj1[p])) {
				continue;
			}

			if (obj1[p] != obj2[p]) {
				return false;
			}
		}
		return true;
	},

	getSearchFiedValues : function(type) {
		var ctnSearch = this.down('#ctnSearch');
		var values = [];

		Ext.Array.each(ctnSearch.items.items, function(searchfield) {
			if (!searchfield.isFormField)
				return;
			var value = searchfield.getValue();
			if (value) {
				if (type == 'conditions') {
					values.push({
						column : searchfield.getName(),
						value : value + '%',
						operator : 'like'
					});
				} else if (type == 'filters') {
					values.push({
						property : searchfield.getName(),
						value : value
					});
				}
			}
		}, this);

		return values;
	},

	createSearchFields : function() {
		var searchFields = [];

		Ext.Array.each(this.pColumns, function(col) {
			if (!col.hidden) {
				var self = this;

				searchFields.push({
					xtype : 'textfield',
					name : col.dataIndex,
					hideLabel : true,
					readOnly : col.disabledSearch || false,
					emptyText : col.text || col.header,
					flex : col.flex,
					listeners : {
						specialkey : function(textfield, e) {
							if (e.getKey() == e.ENTER) {
								self.viewCodeList();
							}
						}
					}
				});
			}
		}, this);

		return searchFields;
	},

	clearSearchFields : function() {
		var ctnSearch = this.down('#ctnSearch');
		Ext.Array.each(ctnSearch.items.items, function(searchfield) {
			if (!searchfield.isFormField)
				return;
			searchfield.setValue('');
		}, this);
	},

	reconfigureGrdSelectCodeList : function() {
		var self = this;
		var fields = [];
		var columns = [ {
			xtype : 'actioncolumn',
			iconCls : 'iconFileDelete',
			align : 'center',
			width : 30,
			handler : function(gridview, rowIndex, colIndex) {
				var grid = gridview.up();
				self.removeSelectedRecord(grid.itemId, grid.getStore().getAt(rowIndex));
			}
		} ];

		Ext.Array.each(this.pColumns, function(column) {
			fields.push(column.dataIndex);
			var col = Ext.clone(column);
			if (!col.fieldId) {
				col.hidden = true;
			}
			columns.push(col);
		}, this);

		var store = Ext.create('Ext.data.Store', {
			fields : fields
		});

		this.down('#grdSelectCodeList').reconfigure(store, columns);

		var values = this.pSelectedValues || [];
		store.loadData(values);
	},

	buildForm : function() {
		var self = this;

		return {
			xtype : 'panel',
			flex : 1,
			layout : {
				type : 'hbox',
				align : 'stretch'
			},
			items : [ {
				xtype : 'gridpanel',
				itemId : 'grdCodeList',
				sortableColumns : false,
				enableColumnHide : false,
				enableColumnMove : false,
				columnLines : true,
				// cls : 'navyGrid',
				selModel : Ext.create('Ext.selection.RowModel', {
					mode : 'SIMPLE'
				}),
				flex : 1,
				columns : this.pColumns,
				store : this.pStore,
				dockedItems : [ {
					xtype : 'panel',
					height : 39,
					cls : 'windowSearchField',
					dock : 'bottom',
					layout : {
						type : 'hbox',
						align : 'stretch'
					},
					items : [ {
						xtype : 'container',
						itemId : 'ctnSearch',
						items : this.createSearchFields(),
						flex : 1,
						layout : {
							type : 'hbox',
							align : 'stretch'
						}
					}, {
						xtype : 'button',
						itemId : 'btnClearSearchFields',
						iconCls : 'ux-codeview-clearBtn navClearBtn',
						margin : '0 0 0 2',
						tooltip : 'Clear Search Fields'
					} ]
				}, {
					xtype : 'pagingtoolbar',
					itemId : 'barPaging',
					store : this.pStore,
					cls : 'codeviewpagebar',
					displayInfo : true,
					beforePageText : '',
					displayMsg : '{1} / {2}',
					afterPageText : '/ {0}',
					dock : 'bottom',
					doRefresh : function() {
						self.viewCodeList();
					},
					items : [ {
						xtype : 'button',
						itemId : 'btnReset',
						text : 'Fields Reset'
					} ]
				} ]
			}, {
				xtype : 'panel',
				width : 200,
				layout : 'fit',
				items : [ {
					xtype : 'gridpanel',
					itemId : 'grdSelectCodeList',
					sortableColumns : false,
					enableColumnHide : false,
					enableColumnMove : false,
					columnLines : true,
					margin : '0 0 0 3',
					selModel : Ext.create('Ext.selection.RowModel', {
						mode : 'MULTI'
					}),
					border : true,
					viewConfig : {
						plugins : {
							ptype : 'gridviewdragdrop'
						}
					},
					columns : []
				} ],
				dockedItems : [ {
					xtype : 'toolbar',
					dock : 'bottom',
					ui : 'footer',
					height : 39,
					items : [ {
						xtype : 'button',
						itemId : 'btnClear',
						text : 'Clear',
						width : 50
					}, {
						xtype : 'tbfill'
					}, {
						xtype : 'button',
						itemId : 'btnOk',
						text : 'OK',
						width : 50
					}, {
						xtype : 'button',
						itemId : 'btnClose',
						text : 'Close',
						width : 50
					} ]
				} ]
			} ]
		};
	}
});